<template>
  <foreignObject
    :x="value.x1"
    :y="value.y1"
    :width="value.w1 + 10"
    :height="value.h1"
    @mousedown.stop="() => {}"
    :id="lid"
    @click.stop="value.click(lid)"
  >
    <input
      v-if="value.focus"
      :style="{
        height: `${value.h1}px`,
        width: `${value.w1}px`,
      }"
      v-on:blur="inpBlur"
      :ref="lid"
      v-focus
      v-model="value.value"
      type="text"
      v-on:input="inpChange"
      style="color: black"
    />
    <text
      :id="`q${lid}`"
      :font-size="`${value.fontSize}px`"
      :height="`${value.h1}px`"
      @dblclick="textClick()"
      stroke-width="0"
      style="color: black; cursor: text; display: inline-block"
      v-else
      >{{ value.value }}</text
    >
  </foreignObject>
</template>
<script>
var Enumerable = require("linq");
export default {
  props: {
    lid: null,
    value: {
      x1: 0,
      y1: 0,
      w1: 30,
      h1: 30,
      fontSize: 16,
      focus: false,
    },
  },
  created() {},
  mounted() {
    this.$nextTick(() => {
      const test = document.getElementById(`q${this.$props.lid}`);
      test.style.fontSize = `${this.$props.value.fontSize}px`;
      //this.$refs.svginp.focus();
      //document.getElementById(this.lid).focus();
    });
  },
  watch: {
    "$store.state.figureParameter.fontSize": {
      handler: function (newName, oldName) {
        const test = document.getElementById(`q${this.$store.state.beforeId}`);
        test.style.fontSize = `${newName}px`;
      },
      deep: true,
    },
  },
  methods: {
    bodyClick() {
      this.value.click(this.lid);
    },
    textClick() {
      this.value.focus = true;
      this.$nextTick(() => {
        this.$refs[this.lid].focus();
      });
    },
    //设置输入框的宽
    setInputWeight(e) {
      if (this.value.value == "") return;
      if (this.value.value.length > 0 && this.value.value) {
        //判断是中文还是英文 中文占1个fontsize 其他占0.5个
        var pattern = new RegExp("[\u4E00-\u9FA5]+");
        var fontSize = this.value.fontSize;
        //console.log(Enumerable.from(this.value.value).where(p => pattern.test(p)).count());
        var widght =
          Enumerable.from(this.value.value)
            .where((p) => pattern.test(p))
            .count() *
            fontSize +
          (Enumerable.from(this.value.value)
            .where((p) => !pattern.test(p))
            .count() *
            fontSize) /
            2 +
          fontSize / 2;
        if (widght < 30) widght = 30;
        this.value.w1 = widght;
      }
    },
    inpChange(e) {
      this.setInputWeight(e);
    },
    //失去焦点
    inpBlur(e) {
      this.value.focus = false;
    },
  },
};
</script>
<style>
input {
  border: none;
  -webkit-appearance: none; /*去除阴影边框*/
  outline: none;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0); /*点击高亮的颜色*/
  padding: 0;
}
</style>
